package com.apa7.keepaccounts.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.apa7.keepaccounts.dto.ReturnData;
import com.apa7.keepaccounts.util.BodyReaderRequestWrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.LinkedHashMap;

public class WebInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(WebInterceptor.class);

    @Value("${sign.key}")
    private String signKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String json="";
        try {
            //获取数据
            BodyReaderRequestWrapper servletRequestWrapper = new BodyReaderRequestWrapper(request);
            json= servletRequestWrapper.getBodyString(request);
            LinkedHashMap<String, String> data=JSON.parseObject(json,new TypeReference<LinkedHashMap<String, String>>(){} );

            //验证时间戳
            long time=System.currentTimeMillis()/1000;
            if(Long.parseLong(data.get("time"))>time+60||Long.parseLong(data.get("time"))<time-60){
                response.setHeader("content-type","application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println(JSON.toJSONString(new ReturnData(500,"请求已过期")));
                return false;
            }

            //验证签名
            StringBuilder signSb= new StringBuilder();
            for(String k:data.keySet()){
                if(!k.equals("sign")){
                    signSb.append(k).append("=").append(data.get(k));
                }
            }
            signSb.append("signKey=").append(signKey);

            String sign=DigestUtils.md5Hex(signSb.toString().toUpperCase());
            if(!data.get("sign").equals(sign)){
                response.setHeader("content-type","application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println(JSON.toJSONString(new ReturnData(500,"签名验证不正确！")));
                return false;
            }

            return true;
        }catch (Exception e){
            //日志操作
            logger.error("---系统发生异常---");
            logger.error("发生错误");
            logger.error("请求URL");
            logger.error(request.getRequestURL().toString());
            logger.error("参数信息");
            logger.error(json);
            logger.error("其他信息");
            logger.error(getExceptionAllinformation_01(e));
            logger.error("错误信息："+e.getMessage());
            logger.error("错误原信息：");
            logger.error(JSON.toJSONString(e));
            logger.error("---以上为异常信息---");

            response.setHeader("content-type","application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSON.toJSONString(new ReturnData(500,"参数无法读取！")));
            return false;
        }
    }

    private String getExceptionAllinformation_01(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
        }
        return ret;
    }
}
